import Vue from 'vue'
import Router from 'vue-router'
// import store from 'store/modules/login'
import { auth } from 'utils'

Vue.use(Router)

/**
 * Asynchronously load view
 * @subdir {string} 二级目录
 * @name  {string} vue文件名
 */
function load(subdir, name) {
  name = name || subdir
  return resolve => require([`../views/${subdir}/${name}.vue`], resolve) // eslint-disable-line
}

// meta: { requireAuth: true } 表示需要登录拦截的路由
const routes = [{
  path: '/',
  component: load('home'),
}, {
  path: '/home',
  component: load('home'),
}, {
  path: '/signUpGetCoupon',
  component: load('coupon', 'signUpGetCoupon'),
}, {
  path: '/advertisement',
  component: load('home', 'advertisement'),
}, {
  path: '/compilationsTheme',
  component: load('goodsTheme'),
}, {
  path: '/address',
  component: load('address'),
  meta: { requireAuth: true },
}, {
  path: '/addressList',
  component: load('address', 'addressList'),
  meta: { requireAuth: true },
}, {
  path: '/goodsInfo',
  component: load('goodsInfo'),
}, {
  path: '/orderConfirmation',
  component: load('order', 'orderConfirmation'),
  meta: { requireAuth: true },
}, {
  path: '/orderResult',
  component: load('order', 'orderResult'),
  meta: { requireAuth: true },
}, {
  path: '/login',
  component: load('login'),
  children: [{
    path: '',
    component: load('login', 'indexPage'),
  }, {
    path: 'byEmail',
    component: load('login', 'byEmail'),
  }, {
    path: 'byPhone',
    component: load('login', 'byPhone'),
  }, {
    path: 'passwd',
    component: load('login', 'passwd'),
  }, {
    path: 'verifyCode',
    component: load('login', 'verifyCode'),
  }],
}]

const router = new Router({
  mode: 'history',
  routes,
})

router.onReady(() => {
  const channel = router.currentRoute.query.c

  if (channel) {
    sessionStorage.channel = channel
  }
})

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if (auth.isLogin()) {
      next()
    } else {
      sessionStorage.redirect = to.fullPath
      next({
        path: '/login',
      })
    }
  } else {
    next()
  }
})

export default router
